<?php
/**
 * 前台登录 退出操作
 *
 *
 *
 *
 
 */

//use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');

class loginControl extends mobileHomeControl {

	public function __construct(){
		parent::__construct();
	}

	/**
	 * 登录
	 */
	public function indexOp(){
        if(empty($_POST['username']) || empty($_POST['password']) || !in_array($_POST['client'], $this->client_type_array)) {
            output_error('登录失败');
        }

        $model_member = Model('member');

        $array = array();
        $array['member_name']	= $_POST['username'];
        //$array['member_passwd']	= md5($_POST['password']);
        $array['member_passwd'] = $_POST['password'];
        $member_info = $model_member->getMemberInfo($array);
        if(!empty($member_info)) {
            if($member_info['mobile_attribution']==null){
                //$url='http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel='. $member_info['mobile'].'&t='.time();;
                //$content = $this->get_mobileArea($val['member_mobile']);
                //echo $member_info['member_mobile'];
                $content=$this->get_mobileArea($member_info['member_mobile']);
                //echo $content;
                //__GetZoneResult_ = { mts:'1773660', province:'广西', catName:'中国电信', telString:'17736600405', areaVid:'30518', ispVid:'138238560', carrier:'广西电信' } 	             //$aa=$content->__GetZoneResult_;
                // 	            //echo $content;
                preg_match_all("/(\w+):'([^']+)/", $content, $m);
                $mobile = array_combine($m[1], $m[2]);
                $data['mobile_attribution']=$mobile['carrier'];
                //写入
                $result=$model_member->editMember($array, $data);
                /* if($result){
                    echo '写入成功';
                } */
            }
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_POST['client']);
            if($token) {
                output_data(array('username' => $member_info['member_name'], 'key' => $token));
            } else {
                output_error('登录失败');
            }
        } else {
            output_error('用户名密码错误');
        }
    }

    /**
     * 登录生成token
     */
    private function _get_token($member_id, $member_name, $client) {
        $model_mb_user_token = Model('mb_user_token');

        //重新登录后以前的令牌失效
        //暂时停用
        //$condition = array();
        //$condition['member_id'] = $member_id;
        //$condition['client_type'] = $_POST['client'];
        //$model_mb_user_token->delMbUserToken($condition);

        //生成新的token
        $mb_user_token_info = array();
        $token = md5($member_name . strval(TIMESTAMP) . strval(rand(0,999999)));
        $mb_user_token_info['member_id'] = $member_id;
        $mb_user_token_info['member_name'] = $member_name;
        $mb_user_token_info['token'] = $token;
        $mb_user_token_info['login_time'] = TIMESTAMP;
        $mb_user_token_info['client_type'] = $_POST['client'];

        $result = $model_mb_user_token->addMbUserToken($mb_user_token_info);

        if($result) {
            return $token;
        } else {
            return null;
        }

    }

	/**
	 * 注册
	 */
	public function registerOp(){
		$model_member	= Model('member');

        $register_info = array();
        $register_info['username'] = $_POST['username'];
        $register_info['password'] = $_POST['password'];
        $register_info['password_confirm'] = $_POST['password_confirm'];
        //$register_info['email'] = $_POST['email'];
        $register_info['mobile'] = $_POST['mobile'];
        
        //查找手机归属地
        //$url='http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel='. $register_info['mobile'].'&t='.time();;
        //$content = $this->get_mobileArea($val['member_mobile']);
        $content=$this->get_mobileArea($register_info['mobile']);
        //__GetZoneResult_ = { mts:'1773660', province:'广西', catName:'中国电信', telString:'17736600405', areaVid:'30518', ispVid:'138238560', carrier:'广西电信' } 	             //$aa=$content->__GetZoneResult_;
        // 	            //echo $content;   
        preg_match_all("/(\w+):'([^']+)/", $content, $m);
        $mobile = array_combine($m[1], $m[2]);
        $register_info['mobile_attribution']=$mobile['carrier'];
        
        $member_info = $model_member->register($register_info);
        if(!isset($member_info['error'])) {
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_POST['client']);
            if($token) {
                output_data(array('username' => $member_info['member_name'], 'key' => $token));
            } else {
                output_error('注册失败');
            }
        } else {
            output_error($member_info['error']);
        }
    }
    
    
    /**
     * 抓取手机信息
     */
    function get_mobileArea($mobile){
        $url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=".$mobile."&t=".time();
        $content = file_get_contents($url);
        return mb_convert_encoding($content, 'utf-8', 'GBK,UTF-8,ASCII');
    }
    
    /**
     * 抓取网页
     * @param unknown $url
     */
    public function get_mobile_area($mobile){
        $url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=".$mobile;
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //函数中加入下面这条语句
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        $output = mb_convert_encoding($output, 'utf-8', 'GBK,UTF-8,ASCII');
         
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        return ($output);
    }
    
    /**
     * web注册
     */
    public function webregisterOp(){
        $model_member	= Model('member');
        
        $register_info = array();
        $register_info['username'] = $_POST['username'];
        //对password进行加密处理
        $output = md5(md5($_POST['password'])+$_POST['username']);
        $register_info['password'] = $output;
        $register_info['password_confirm'] = $output;
        //$register_info['email'] = $_POST['email'];
        $register_info['mobile'] = $_POST['username'];
        $member_info = $model_member->register($register_info);
        if(!isset($member_info['error'])) {
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_POST['client']);
            if($token) {
                output_data(array('username' => $member_info['member_name'], 'key' => $token));
            } else {
                output_error('注册失败');
            }
        } else {
            output_error($member_info['error']);
        }
    }
    /**
     * web注册测试
     */
    public function webregistertestOp(){
        $model_member	= Model('member');
        
        $register_info = array();
        $register_info['username'] = $_GET['username'];
        //对password进行加密处理
        $output = md5(md5($_GET['password'])+$_GET['username']);
        $register_info['password'] = $output;
        $register_info['password_confirm'] = $output;
        //$register_info['email'] = $_POST['email'];
        $register_info['mobile'] = $_GET['username'];
        $member_info = $model_member->register($register_info);
        if(!isset($member_info['error'])) {
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_GET['client']);
            if($token) {
                output_data(array('username' => $member_info['member_name'], 'key' => $token));
            } else {
                output_error('注册失败');
            }
        } else {
            output_error($member_info['error']);
        }
    }
    
    public function smscodeOp($mobile='')
     {
        //if (!empty($_POST['mobile'])) {
        //    $tpl_id = '1192361';
        //    $this->_sendSms($_POST['mobile'],$tpl_id);
        //}else{
        //    output_error('请输入手机号码！');
        //}
         
         if (!empty($_POST['mobile'])) {
             $mobile = $_POST['mobile'];
             $model_member = Model('member');
             $array = array();
             $array['member_mobile'] = $mobile;
             $member_info = $model_member->getMemberInfo($array);
             if(!empty($member_info)) {
                 output_error('该手机号码已经注册！');
             }else{
                 $tpl_id = '1192361';
                 $this->_sendSms($mobile,$tpl_id);
             }
         }else{
             output_error('请输入手机号码！');
         }
     }
    
    /**
    * 产生一个指定长度的随机字符串,并返回给用户
    * @access public
    * @param int $len 产生字符串的位数
    * @return string
    */
    private function _randstr($len=6) {
        $chars='0123456789';
        mt_srand((double)microtime()*1000000*getmypid());
        $password='';
        while(strlen($password)<$len)
            $password.=substr($chars,(mt_rand()%strlen($chars)),1);
        return $password;
    }

    private function _sendSms($mobile,$tpl_id){
        $code = $this->_randstr(4);
        $sms = new Sms();
        $content = ('#code#').'='.urlencode($code);
        $result = $sms->mytpl_send_sms($tpl_id,$mobile,$content);
        if ($result) {
            output_data(array('mobile' => $mobile, 'code' => $code,'msg'=>'短信发送成功！'));
        }else{
            output_error('短信发送失败，请检测手机号码格式！');
        }
    }

	/**
     * 头像上传
     */
    public function avatar_uploadOp() {
        import('function.thumb');
        $member_id = '2';
        //上传图片
        $upload = new UploadFile();
        $upload->set('thumb_width', 500);
        $upload->set('thumb_height',499);
        $ext = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
        $upload->set('file_name',"avatar_$member_id.$ext");
        $upload->set('thumb_ext','_new');
        $upload->set('ifremove',true);
        $upload->set('default_dir',ATTACH_AVATAR);
        if (!empty($_FILES['pic']['tmp_name'])){
            $result = $upload->upfile('pic');
            if (!$result){
                output_error($upload->error);
            }
        }else{
            output_error('上传失败，请尝试更换图片格式或小图片');
        }
    }

    /**
     * 验证手机号是否注册
     */
    public function checkMobileOp()
    {
        if (!empty($_POST['mobile'])) {
            $mobile = $_POST['mobile'];
            $model_member = Model('member');
            $array = array();
            $array['member_mobile'] = $mobile;
            $member_info = $model_member->getMemberInfo($array);
            if(!empty($member_info)) {
                $tpl_id = '1192361';
                $this->_sendSms($mobile,$tpl_id);
            }else{
                output_error('该手机号码尚未注册！');
            }
        }else{
            output_error('请输入手机号码！');
        }
    }

    /**
     * 重置密码
     */
    public function reSetPassWordOp()
    {
        if (!empty($_POST['mobile'])) {
            if (!empty($_POST['password'])) {
                if (!empty($_POST['password_confirm'])) {
                    $mobile = $_POST['mobile'];
                    $password = $_POST['password'];
                    $model_member = Model('member');
                    $array = array();
                    $array['member_mobile'] = $mobile;
                    $data = $model_member->getMemberInfo($array);
                    if(!empty($data)) {
                        $data['member_passwd']=trim($password);
                        if($model_member->editMember($array,$data)){
                            output_data(array('msg'=>'操作成功！'));
                        }else{
                            output_error('操作失败');
                        }
                    }else{
                        output_error('该手机号码尚未注册！');
                    }
                } else {
                    output_error('请输入确认的密码！');
                }
            } else {
                output_error('请输入新的密码！');
            }
        }else{
            output_error('请输入手机号码！');
        }
    }
}
